package com.sita.linboard.login;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.InputType;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.readystatesoftware.systembartint.SystemBarTintManager;
import com.sita.linboard.LinBoardDao.DaoSingleTon;
import com.sita.linboard.LinBoardDao.UserInfo;
import com.sita.linboard.LinBoardDao.UserInfoDao;
import com.sita.linboard.MainMessage.MainActivity;
import com.sita.linboard.R;
import com.sita.linboard.WelcomeActivity;
import com.sita.linboard.base.ActivityCollector;
import com.sita.linboard.base.BaseApplication;
import com.sita.linboard.http.RestClient;
import com.sita.linboard.utils.SpUtils;
import com.sita.linboard.utils.ToastUtils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;

/**
 * Created by Jason on 2016/8/29.
 * //HXID:439435360729041973
 */
public class DriverLoginActivity extends Activity implements View.OnClickListener {
    private EditText login_phone, login_passp;
    private TextView intoForgetPass;
    private Button login_confirm, login_register;
    private LoginBackBean bean;
    private UserInfo userInfo;
    private UserInfoDao userInfoDao;
    private long firstTime = 0;
    private ProgressDialog dialog;

    public static void DriverLoginIntent(Context context) {
        Intent intent = new Intent(context, DriverLoginActivity.class);
        context.startActivity(intent);
    }

    public static boolean isPhoneNumberValid(String phoneNumber) {
        boolean isValid = false;
       /*
	    * 可接受的电话格式有：
	    */
        String expression = "^\\(?(\\d{3})\\)?[- ]?(\\d{3})[- ]?(\\d{5})$";
	   /*
	    * 可接受的电话格式有：
	    */
        String expression2 = "^\\(?(\\d{3})\\)?[- ]?(\\d{4})[- ]?(\\d{4})$";
        CharSequence inputStr = phoneNumber;
        Pattern pattern = Pattern.compile(expression);
        Matcher matcher = pattern.matcher(inputStr);

        Pattern pattern2 = Pattern.compile(expression2);
        Matcher matcher2 = pattern2.matcher(inputStr);
        if (matcher.matches() || matcher2.matches()) {
            isValid = true;
        }
        return isValid;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (SpUtils.getBoolean("isLogin", false, BaseApplication.getContext())) {
            MainActivity.getMainIntent(this);
            this.finish();
        }

        ActivityCollector.addActivity(this);
        setContentView(R.layout.activity_driverlogin);
        setSystemBar(R.color.main_title_bg);
        initView(savedInstanceState);
        initData();
    }

    private void initData() {
        login_confirm.setOnClickListener(this);
        login_register.setOnClickListener(this);
        intoForgetPass.setOnClickListener(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ActivityCollector.removeActivity(this);
    }

    private void initView(Bundle savedInstanceState) {
        login_phone = (EditText) findViewById(R.id.driver_login_phone);
        login_passp = (EditText) findViewById(R.id.driver_login_pass);
        login_passp.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);

        login_confirm = (Button) findViewById(R.id.driver_login_confirm);
        login_register = (Button) findViewById(R.id.driver_register);
        intoForgetPass = (TextView) findViewById(R.id.forget);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.driver_login_confirm:
                dialog = ProgressDialog.show(DriverLoginActivity.this, null, "正在登录中...");
                if (isPhoneNumberValid(login_phone.getText().toString())) {
                    drivreLogin();
                } else {
                    ToastUtils.showLong("手机号码有误！请重新输入");
                }
                break;
            case R.id.driver_register:
                RegisteredFirstActivity.RegisterFirstIntent(this);
                break;
            case R.id.forget:
                ForgetPassActivity.ForgetPassIntent(this, 1);
                break;
        }
    }

    private void drivreLogin() {
        LoginRequest request = new LoginRequest();
        if (login_phone.getText().length() != 0 && login_passp.getText().length() != 0) {
            request.mobile = login_phone.getText().toString();
            request.password = login_passp.getText().toString();
            request.loginType = 2;//2司机端
        } else {
            ToastUtils.showLong("输入有误");
        }

        RestClient.getRestService().login(request, new Callback<LoginBackBean>() {
            @Override
            public void success(LoginBackBean loginBackBean, Response response) {
                if (response.getStatus() == 200) {
                    if (loginBackBean.getErrorCode().equals("0")) {
                        bean = loginBackBean;
                        SpUtils.putString("AccoundID", bean.getData().getAccount().getAccountId(), BaseApplication.getContext());
                        SpUtils.putString("NickName", bean.getData().getAccount().getNickName(), BaseApplication.getContext());
                        SpUtils.putString("mobile", bean.getData().getAccount().getMobile(), BaseApplication.getContext());
                        SpUtils.putBoolean("isLogin", true, BaseApplication.getContext());
                        //HXID:439435360729041973
                        //环信注册
                        EMClient.getInstance().login(bean.getData().getAccount().getAccountId(),
                                bean.getData().getAccount().getImPassword(), new EMCallBack() {
                                    @Override
                                    public void onSuccess() {
                                        EMClient.getInstance().groupManager().loadAllGroups();
                                        EMClient.getInstance().chatManager().loadAllConversations();
                                        dialog.dismiss();
                                        Intent intent = new Intent(DriverLoginActivity.this, WelcomeActivity.class);
                                        startActivity(intent);
                                        finish();
                                    }

                                    @Override
                                    public void onError(int i, String s) {
                                    }

                                    @Override
                                    public void onProgress(int i, String s) {
                                        Log.d("main", "登录聊天服务器失败！");
                                    }
                                });

                    }
                }
            }

            @Override
            public void failure(RetrofitError error) {
                ToastUtils.show("请确认用户名密码填写正确", 3);
                dialog.dismiss();
            }
        });

    }

    private void SavedLocal(LoginBackBean bean) {
        userInfoDao = DaoSingleTon.getInstance().getUserInfoDao();
        userInfo = new UserInfo();
        userInfo.setAccountId(bean.getData().getAccount().getAccountId());
        userInfo.setAddress((String) bean.getData().getAccount().getAddress());
        userInfo.setAvatar(bean.getData().getAccount().getAvatar());
        userInfo.setBirthday((String) bean.getData().getAccount().getBirthday());
        userInfo.setDeptcode((String) bean.getData().getAccount().getDeptcode());
        userInfo.setDeptname((String) bean.getData().getAccount().getDeptname());
        userInfo.setDriver((String) bean.getData().getAccount().getDriver());
        userInfo.setEmail((String) bean.getData().getAccount().getEmail());
        userInfo.setGender(String.valueOf(bean.getData().getAccount().getGender()));
        userInfo.setImPassword(bean.getData().getAccount().getImPassword());
        userInfo.setMobile(bean.getData().getAccount().getMobile());
        userInfo.setNickName(bean.getData().getAccount().getNickName());
        userInfo.setRegisterDate((String) bean.getData().getAccount().getRegisterDate());
        userInfo.setSignature((String) bean.getData().getAccount().getSignature());
        userInfo.setUniqueId(bean.getData().getAccount().getUniqueId());
        userInfo.setUnitTpye((String) bean.getData().getAccount().getUnitTpye());
        userInfo.setUserName((String) bean.getData().getAccount().getUserName());
        userInfoDao.insert(userInfo);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                long secondTime = System.currentTimeMillis();
                if (secondTime - firstTime > 2000) {                                         //如果两次按键时间间隔大于2秒，则不退出
                    Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                    firstTime = secondTime;//更新firstTime
                    return true;
                } else {                                                    //两次按键小于2秒时，退出应用
                    ActivityCollector.finishAll();
                    finish();
                    System.exit(0);
                }
                break;
        }
        return super.onKeyUp(keyCode, event);
    }

    public void setSystemBar(int color) {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            setTranslucentStatus(true);
        }

        SystemBarTintManager tintManager = new SystemBarTintManager(this);
        tintManager.setStatusBarTintEnabled(true);
        tintManager.setStatusBarTintResource(color);//通知栏所需颜色

    }

    @TargetApi(19)
    private void setTranslucentStatus(boolean on) {
        Window win = getWindow();
        WindowManager.LayoutParams winParams = win.getAttributes();
        final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
        if (on) {
            winParams.flags |= bits;
        } else {
            winParams.flags &= ~bits;
        }
        win.setAttributes(winParams);
    }

}
